package com.jmp.security.grant;

import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.RequestDetail;
import com.jmp.security.base.UserDetail;
import com.jmp.security.base.UserDetailValidService;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.mapper.CompanyMapperExt;
import one.stand.model.BusinessCard;
import one.stand.model.Company;
import one.stand.service.BusinessCardBaseService;
import one.stand.util.AssertUtil;

import java.util.Objects;

@Slf4j
public class UserDetailValidServiceImpl<T extends RequestDetail> implements UserDetailValidService<T> {
    private BusinessCardBaseService businessCardBaseService;
    private CompanyMapperExt companyMapperExt;

    public UserDetailValidServiceImpl(BusinessCardBaseService businessCardBaseService, CompanyMapperExt companyMapperExt) {
        this.businessCardBaseService = businessCardBaseService;
        this.companyMapperExt = companyMapperExt;
    }

    @Override
    public void check(T requestDetail, ClientDetail clientDetail, UserDetail userDetail) {
        AssertUtil.nonNull(userDetail.getUserModel(), ResultEnum.PARAM_CHECK, "用户不存在");
        AssertUtil.nonNull(userDetail.getUserModel().getIsDel() == 0, ResultEnum.PARAM_CHECK, "用户不存在");

        if (Objects.isNull(userDetail.getCardModel())) {
            BusinessCard cardModel = businessCardBaseService.getByUserId(userDetail.getUserModel().getUserId());
            userDetail.setCardModel(cardModel);
        }

        if (Objects.nonNull(userDetail.getCardModel()) && Objects.isNull(userDetail.getCompany())) {
            Company company = companyMapperExt.selectByPrimaryKey(userDetail.getCardModel().getCompanyId());
            userDetail.setCompany(company);
        }
    }
}
